var exec = require('child_process').execSync;
var fmt = require('util').format;

function PidFinder(){
  this.cmdarr = [];
  this.awkCmd = '';
};

PidFinder.prototype.pipe = function (cmd){
  this.cmdarr.push(cmd.trim());
  return this;
};


PidFinder.prototype.awk = function(field){
  this.awkCmd = fmt("awk '{print $%d}'",field || 2 );
  return this;
};

PidFinder.prototype.exec = function(){
  var _cmd = '';
  var r = -1;

  if(this.cmdarr.length < 1){
    return r;
  }else if(this.cmdarr.length == 1) {
    _cmd = this.cmdarr[0];
  }else{
    _cmd = this.cmdarr.join('|');
  }

  
  if(!!this.awkCmd){
    _cmd = _cmd + '|' + this.awkCmd;
  }

  // console.log(_cmd);
  if(!!_cmd){
    try{
      var ra = exec(_cmd,[],[]).toString().trim().split('\n');
      if(this.cmdarr.length > 1){
        if(ra.length == 2){
          r = parseInt(ra[0]);
        }        
      }else{
        r = parseInt(ra[0].trim());
      }

    }catch(e){
      console.error('exec cmd error',e);
    }
  }
  return r;
};


 





module.exports = PidFinder;